package cn.bdqn.controller;

import cn.bdqn.pojo.*;
import cn.bdqn.service.*;
import cn.bdqn.tools.PageSupport;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/devController")
public class DeveloperController {
    @Resource
    private AppInfoService appInfoService;
    @Resource
    private AppCategoryService appCategoryService;
    @Resource
    private DataDictionaryService dataDictionaryService;
    @Resource
    private AppVersionService appVersionService;
    @Resource
    private DelService delService;

    //跳转到审核手游页面
    @RequestMapping("/toAppInfoList")
    public String toAppCheckList() {
        return "dev/appinfo";
    }

    //三级分类下拉框
    @ResponseBody
    @RequestMapping(value = "/levelCassify", produces = {"application/json;charset=utf-8"})
    public Object levelCassify(@RequestParam(required = false, defaultValue = "1") int parentId) {
        List<AppCategory> category = appCategoryService.getParentId(parentId);
        return JSONArray.toJSONString(category);
    }

    //所属平台
    @ResponseBody
    @RequestMapping(value = "/findApp", produces = {"application/json;charset=utf-8"})
    public Object findApp() {
        List<DataDictionary> app = dataDictionaryService.getDataDictionary();
        return JSONArray.toJSONString(app);
    }

    //手游状态
    @ResponseBody
    @RequestMapping(value = "/gamestatus", produces = {"application/json;charset=utf-8"})
    public Object gamestatus() {
        List<DataDictionary> gamestatus = dataDictionaryService.getDateDictionaryStatus();
        return JSONArray.toJSONString(gamestatus);
    }

    //一级分类
    @ResponseBody
    @RequestMapping(value = "/getLevel1", produces = {"application/json;charset=utf-8"})
    public Object getLevel1() {
        List<AppCategory> level1 = appCategoryService.getLevel1();
        return JSON.toJSONString(level1);
    }

    //分页
    @RequestMapping("/toDevAppList")
    public String toDevAppList(HttpServletRequest request, AppInfo appInfo, @RequestParam(defaultValue = "1") Integer pageIndex) {
        PageSupport page = new PageSupport();
        page.setCurrentPageNo(pageIndex);
        appInfo.setDevId(((DevUser) request.getSession().getAttribute("devUser")).getId());
        page.setTotalCount(appInfoService.getDevAppInfoListCount(appInfo));
        List<AppInfo> devAppInfoList = appInfoService.getDevAppInfoList(appInfo, (page.getCurrentPageNo() - 1) * page.getPageSize(), page.getPageSize());
        request.setAttribute("devAppInfoList", devAppInfoList);
        request.setAttribute("page", page);
        return "/dev/appinfo";
    }

    //跳转新增页面
    @RequestMapping("/toDevAdd")
    public String toDevAdd() {
        return "dev/appinfoadd";
    }

    //新增手游信息
    @ResponseBody
    @RequestMapping("/addAppInfo")
    public String addAppInfo(AppInfo appInfo, HttpServletRequest request, @RequestParam(value = "a_logoPicPath") MultipartFile a_logoPicPath) {
        if (!a_logoPicPath.isEmpty()) {
            String path = "D:\\BCSP_S3\\uploadfile";
            String originalFile = a_logoPicPath.getOriginalFilename();
            String prefix = FilenameUtils.getExtension(originalFile);
            int filesize = 500000000;
            if (a_logoPicPath.getSize() > filesize) {
                request.setAttribute("uploadFileError", "上传文件不能大于50KB");
                return "/dev/appinfoadd";
            } else if (prefix.equalsIgnoreCase("jpg") ||
                    prefix.equalsIgnoreCase("jpeg") ||
                    prefix.equalsIgnoreCase("png")) {
                String uuid = UUID.randomUUID() + "." + prefix;
                File file = new File(path);
                appInfo.setLogoLocPath(path + "/" + uuid);
                appInfo.setLogoPicPath(File.separator + "uploadfile" + File.separator + uuid);
                if (!file.exists()) {
                    file.mkdirs();
                }
                try {
                    a_logoPicPath.transferTo(new File(file, uuid));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (!prefix.equalsIgnoreCase("jpg") ||
                    !prefix.equalsIgnoreCase("jpeg") ||
                    !prefix.equalsIgnoreCase("png")) {
                request.setAttribute("uploadFileImgError", "上传文件格式必须为jpg、jpeg、png");
                return "false";
            }
        }
        DevUser devUser = (DevUser) request.getSession().getAttribute("devUser");
        appInfo.setCreatedBy(devUser.getId());
        appInfo.setDevId(devUser.getId());
        appInfo.setCreationDate(new Date());
        if (appInfoService.addAppInfo(appInfo) > 0) {
            return "true";
        }
        return "false";
    }

    //跳转修改页面
    @RequestMapping("/toDevModify")
    public String toDevModify(HttpSession session, @Param("aid") Integer aid) {
        AppInfo appInfo = appInfoService.getAppInfoId(aid);
        session.setAttribute("appInfo", appInfo);
        return "dev/appmodify";
    }

    //修改手游信息
    @RequestMapping("/doUpdate")
    public String doUpdate(AppInfo appInfo, HttpServletRequest request, @RequestParam(value = "attach", required = false) MultipartFile attach) {
        if (!attach.isEmpty()) {
            String path = "D:\\BCSP_S3\\uploadfile";
            String originalFile = attach.getOriginalFilename();
            String prefix = FilenameUtils.getExtension(originalFile);
            int filesize = 50000000;
            if (attach.getSize() > filesize) {
                request.setAttribute("uploadFileError", "上传文件不能大于50KB");
                return "/dev/appmodify";
            } else if (
                    prefix.equalsIgnoreCase("jpg") ||
                            prefix.equalsIgnoreCase("jpeg") ||
                            prefix.equalsIgnoreCase("png")) {
                String uuid = UUID.randomUUID() + "." + prefix;
                File file = new File(path);
                appInfo.setLogoLocPath(path + "\\" + uuid);
                appInfo.setLogoPicPath(File.separator + "uploadfile" + File.separator + uuid);
                if (!file.exists()) {
                    file.mkdirs();
                }
                try {
                    attach.transferTo(new File(file, uuid));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        DevUser devUser = (DevUser) request.getSession().getAttribute("devUser");
        appInfo.setDevId(devUser.getId());
        appInfo.setModifyBy(devUser.getId());
        appInfo.setDevId(devUser.getId());
        appInfo.setModifyDate(new Date());
        appInfo.setCreatedBy(devUser.getId());
        if (appInfoService.doUpdate(appInfo) > 0) {
            return "redirect:/devController/toDevAppList";
        } else {
            return "/dev/appmodify";
        }
    }

    //APKName重名判断
    @ResponseBody
    @PostMapping("/apkexist")
    public String apkExist(String APKName) {
        String str = "";
        if (appInfoService.findApkName(APKName) > 0) {
            str = "exist";
        } else {
            str = "empty";
        }
        return str;
    }

    //跳转查看页面
    @RequestMapping("/toDevView")
    public String toDevView(HttpSession session, @Param("aid") Integer aid) {
        AppInfo appInfo = appInfoService.getAppInfoId(aid);
        List<AppVersion> appVersionList = appVersionService.selectAppInfoVersion(aid);
        session.setAttribute("appVersionList", appVersionList);
        session.setAttribute("appInfo", appInfo);
        return "dev/appview";
    }

    //删除图片
    @ResponseBody
    @RequestMapping("/delImg/{id}")
    public String delImg(@PathVariable int id) {
        AppInfo appInfoId = appInfoService.getAppInfoId(id);
        String logoPath = appInfoId.getLogoLocPath();
        File file = new File(logoPath);
        if (appInfoService.updateFile(id) > 0) {
            file.delete();
            return "true";
        } else {
            return "false";
        }
    }

    //跳转新增版本信息页面
    @RequestMapping("/toVersionAdd")
    public String toVersionAdd(@Param("id") Integer id, HttpServletRequest request, HttpSession session) {
        List<AppVersion> appVersionList = appVersionService.selectAppInfoVersion(id);
        request.setAttribute("appId", id);
        request.setAttribute("appVersionList", appVersionList);
        return "/dev/versionadd";
    }

    //新增版本信息
    @RequestMapping("/versionadd")
    public String addVersion(AppVersion version, MultipartFile a_downloadLink, HttpServletRequest request) {
        if (!a_downloadLink.isEmpty()) {
            String path = "D:\\BCSP_S3\\uploadfile";
            String originalFile = a_downloadLink.getOriginalFilename();
            String prefix = FilenameUtils.getExtension(originalFile);
            int filesize = 500000000;
            if (a_downloadLink.getSize() > filesize) {
                request.setAttribute("uploadFileError", "上传文件不能大于50KB");
                return "/dev/versionadd";
            } else if (!prefix.equalsIgnoreCase("apk")) {
                request.setAttribute("uploadFileApkError", "上传文件格式必须为apk");
                return "/dev/versionadd";
            } else if (prefix.equalsIgnoreCase("apk")) {
                String uuid = UUID.randomUUID() + "." + prefix;
                File targeFile = new File(path);
                version.setApkLocPath(path + "\\" + uuid);
                version.setDownloadLink(File.separator + "uploadfile" + File.separator + uuid);
                version.setApkFileName(uuid);
                if (!targeFile.exists()) {
                    targeFile.mkdirs();
                }
                try {
                    a_downloadLink.transferTo(new File(targeFile, uuid));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        DevUser user = (DevUser) request.getSession().getAttribute("devUser");
        version.setCreatedBy(user.getId());
        version.setCreationDate(new Date());
        appVersionService.addAppVersion(version);
        appInfoService.updateVersionId(version.getAppId(), version.getId());
        return "redirect:/devController/toDevAppList";
    }

    //跳转修改版本信息页面
    @RequestMapping("/toUpdateVersion")
    public String toUpdateVersion(HttpServletRequest request, @Param("aid") Integer aid, @Param("vid") Integer vid) {
        AppVersion appVersion = appVersionService.getAppVersion(vid);
        request.setAttribute("appVersion", appVersion);
        List<AppVersion> appVersionList = appVersionService.selectAppInfoVersion(aid);
        request.setAttribute("appVersionList", appVersionList);
        return "/dev/versionmodify";
    }

    //修改版本信息
    @RequestMapping("/updateVersion")
    public String updateVersion(AppVersion version, MultipartFile attach, HttpServletRequest request) {
        if (!attach.isEmpty()) {
            String path = "D:\\BCSP_S3\\uploadfile";
            String originalFile = attach.getOriginalFilename();
            String prefix = FilenameUtils.getExtension(originalFile);
            int filesize = 500000000;
            if (attach.getSize() > filesize) {
                request.setAttribute("uploadFileError", "上传文件不能大于50KB");
                return "/dev/versionmodify";
            } else if (prefix.equalsIgnoreCase("apk")) {
                String uuid = UUID.randomUUID() + "." + prefix;
                File file = new File(path);
                version.setApkLocPath(path + "\\" + uuid);
                version.setDownloadLink(File.separator + "uploadfile" + File.separator + uuid);
                version.setApkFileName(uuid);
                if (!file.exists()) {
                    file.mkdirs();
                }
                try {
                    attach.transferTo(new File(file, uuid));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (!prefix.equalsIgnoreCase("apk")) {
                request.setAttribute("uploadFileApkError", "上传文件格式必须为apk");
                return "/dev/versionmodify";
            }
        }
        DevUser user = (DevUser) request.getSession().getAttribute("devUser");
        version.setModifyBy(user.getId());
        version.setModifyDate(new Date());
        appVersionService.updateVersion(version);
        return "redirect:/devController/toDevAppList";
    }

    //删除apk文件（修改）
    @ResponseBody
    @RequestMapping("/delFile/{id}")
    public String delFile(@PathVariable int id) {
        AppVersion appVersion = appVersionService.getAppVersion(id);
        String apkLocPath = appVersion.getApkLocPath();
        File file = new File(apkLocPath);
        if (appVersionService.updateFile(id) > 0) {
            file.delete();
            return "true";
        } else {
            return "false";
        }
    }

    //上架、下架
    @RequestMapping("/appPut")
    public String appPut(Integer status, Integer id, Integer checkId) {
        String str = "";
        if (status == 5 || status == 2) {
            status = 4;
        } else if (status == 4) {
            status = 5;
        }
        int appInfo = appInfoService.updateAppInfo(id, status, checkId);
        if (appInfo > 0) {
            return "redirect:/devController/toDevAppList";
        } else {
            return "/dev/appinfo";
        }
    }

    //删除 （先判断是否有版本信息）
    @ResponseBody
    @RequestMapping("/delAppInfo")
    public Object delAppInfo(Integer aid) {
        boolean flag = false;
        List<AppVersion> appVersions = appVersionService.selectAppInfoVersion(aid);
        if (appVersions.size() > 0) {
            for (AppVersion app : appVersions) {
                if (app.getApkLocPath() != null && !app.getApkLocPath().equals("")) {
                    File file = new File(app.getApkLocPath());
                    if (file.exists()) {
                        file.delete();
                    }
                }
            }
        }
        AppInfo appInfoId = appInfoService.getAppInfoId(aid);
        if (appInfoId.getLogoLocPath() != null) {
            File file = new File(appInfoId.getLogoLocPath());
            if (file.exists()) {
                file.delete();
            }
        }
        if (delService.del(aid)) {
            flag = true;
        }
        return JSONArray.toJSONString(flag);
    }
}
